﻿using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System;
namespace DeepEarth.Core.Persistence
{
    public static class JsonSerializer
    {
        public static string Serialize(object o)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(o.GetType());
                serializer.WriteObject(ms, o);

                using (StreamReader reader = new StreamReader(ms))
                {
                    ms.Position = 0;
                    return reader.ReadToEnd();
                }
            }
        }

        public static T Deserialize<T>(string serialized)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(serialized)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }

        public static object Deserialize(string serialized, Type t)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(serialized)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(t);
                return serializer.ReadObject(ms);
            }
        }



    }
}
